﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NDepot.Manager.Base;
using NDepot.Repository.Base;
using NDepot.Repository;
using NDepot.Models.UI;
using NDepot.Models;

namespace NDepot.Manager
{
    public class OrderManager : IOrderManager
    {
        private static IOrderManager _OrderManager;
        private IOrderRepository _OrderRepository;

        private OrderManager(IOrderRepository p)
        {
            _OrderRepository = p;
        }

        public static IOrderManager GetInstance()
        {
            return GetInstance(null);
        }

        public static IOrderManager GetInstance(IOrderRepository p)
        {
            if (_OrderManager != null)
                return _OrderManager;
            else
            {
                if (p == null)
                    p = new OrderRepository();

                _OrderManager = new OrderManager(p);

                return _OrderManager;
            }
        }

        #region Public Method

        public int Count { get { return _OrderRepository.Count; } }

        public void Insert(OrderInput oi, ICollection<CartItem> items)
        {
            Order order = InputToOrder(oi);

            foreach (CartItem item in items)
            {
                LineItem line = FromCartItem(item);
                line.OrderId = order.Id;

                order.LineItems.Add(line);
            }
            _OrderRepository.Insert(order);
        }

        #endregion

        #region Private Method

        private LineItem FromCartItem(CartItem ci)
        {
            LineItem item = new LineItem();
            item.Id = Guid.NewGuid();
            item.ProductId = Guid.Parse(ci.ProductId);
            item.Quantity = ci.Quantity;
            item.TotalPrice = ci.Price;

            return item;
        }

        private Order InputToOrder(OrderInput oi)
        {
            Order order = new Order();
            order.Name = oi.Name;
            order.EMail = oi.EMail;
            order.Address = oi.Address;
            order.PayType = oi.PayType;

            return order;
        }

        #endregion
    }
}